package com.bw.home.ui

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProviders
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bw.common.utils.LogUtils
import com.bw.common.utils.UserUtils
import com.bw.home.R
import com.bw.home.databinding.FragmentHomeDetailCommentBinding
import com.bw.home.databinding.ItemCommentItemBinding
import com.bw.home.intent.CommentIntent
import com.bw.home.model.entity.CommentEntity
import com.bw.home.model.entity.SimpleVideoEntity
import com.bw.home.model.service.CommentModel
import com.bw.home.state.CommentState
import com.bw.home.widget.ReplyBottomDialog
import com.bw.imageloader.ImageLoaderManager
import com.bw.mvicore.ui.BaseMVIFragment
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @author:created by hahajing
 * 时间：2024/4/29 0029
 * 企鹅号:444511958
 * 描述:
 */
class HomeDetailCommentFragment:BaseMVIFragment() {
    private lateinit var binding:FragmentHomeDetailCommentBinding
    private lateinit var model:CommentModel

    private lateinit var simpleVideoEntity: SimpleVideoEntity


    override fun generateModel() {
        model = ViewModelProviders.of(this).get(CommentModel::class.java)
    }

    override fun initEvent() {
        binding.btnHomeDetailCommentPublish.setOnClickListener {
            val content = binding.etHomeDetailCommentContent.text.trim().toString()
            if (content.isBlank()){
                getBaseActivity().showMsg("请输入评论内容")
                return@setOnClickListener
            }
            generateLifeCycleLaunch {

                val userEntity = UserUtils.getCurrentUser()
                if(userEntity==null){
                    val intent = Intent()
                    intent.action = com.bw.common.common.ConstantValue.NET_ERR_401
                    LocalBroadcastManager.getInstance(requireContext()).sendBroadcast(intent)
                    return@generateLifeCycleLaunch
                }

                val entity = CommentEntity(0,content,"",
                    0,0,simpleVideoEntity.item_id,userEntity.nick,
                    arrayListOf(),0,userEntity.id,userEntity.headImg)

//                LogUtils.d("123","entity hashcode:${entity.hashCode().toString()} model hashcode:${model.hashCode()} intents hashcode:${model.intents.hashCode()}")

                val intent = CommentIntent.PublishCommentIntent(entity)
                LogUtils.d("123","intent hashcode:${intent.hashCode()}")
                model.intents.send(intent)

            }
        }
    }

    override fun generateFragmentRootView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val arg = arguments?.getParcelable<SimpleVideoEntity>("entity")
        simpleVideoEntity = arg!!
        binding=FragmentHomeDetailCommentBinding.inflate(inflater,container,false)
        return binding.root
    }

    override fun lazyLoad() {
        generateLifeCycleLaunch {
            model.intents.send(CommentIntent.GetCommentsIntent(0,simpleVideoEntity.item_id))
        }
    }

    private val adapter:HomeDetailCommentAdapter by lazy {
        HomeDetailCommentAdapter()
    }
    override fun initView() {
        super.initView()
        binding.rvHomeDetailCommentComments.layoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
        binding.rvHomeDetailCommentComments.adapter = adapter
        val pool = RecyclerView.RecycledViewPool()
        binding.rvHomeDetailCommentComments.setRecycledViewPool(pool)



    }

    override fun onResume() {
        super.onResume()
        model.handleIntent()
    }

    override fun handleState() {
        generateLifeCycleLaunch {
            model.state.collect{
                when(it){
                    is CommentState.CommentDefaultState->{}
                    is CommentState.CommentPublishSuccess->{
                        withContext(Dispatchers.Main){
                            binding.etHomeDetailCommentContent.text.clear()
                            adapter.addComment(it.entity)
                            binding.rvHomeDetailCommentComments.scrollToPosition(0)
                            getBaseActivity().showMsg("发布成功")
                        }
                    }
                    is CommentState.CommentGetSuccess->{
                        adapter.appendDatas(it.list)
                    }
                    is CommentState.CommentCommonSuccess->{
                        withContext(Dispatchers.Main){
                            getBaseActivity().showMsg("操作成功")
                        }
                    }
                    is CommentState.CommentFailed->{
                        withContext(Dispatchers.Main){
                            getBaseActivity().showMsg("哎呀出错啦，信息：${it.throwable.message}")
                        }
                    }
                }
            }
        }
    }
}

class HomeDetailCommentAdapter : RecyclerView.Adapter<HomeDetailCommentAdapter.ViewHolder>() {
    private  var datas:MutableList<CommentEntity> = mutableListOf()
    private lateinit var mContext:Context

    fun refresh(_datas:List<CommentEntity>){
        datas=_datas as MutableList<CommentEntity>;
        notifyDataSetChanged()
    }

    fun appendDatas(_datas: List<CommentEntity>){
        datas.addAll(_datas)
        notifyDataSetChanged()
    }

    fun addComment(entity: CommentEntity){
        datas.add(0,entity)
        notifyItemInserted(0)
    }

    class ViewHolder(view:View):RecyclerView.ViewHolder(view) {
        val binding:ItemCommentItemBinding?=ItemCommentItemBinding.bind(view)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        mContext=parent.context
        val view = LayoutInflater.from(mContext).inflate(R.layout.item_comment_item,parent,false)
        return ViewHolder(view)
    }

    override fun getItemCount(): Int {
        return datas.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val entity = datas.get(position)
        if (!entity.userlogo.isBlank()){
            ImageLoaderManager.getInstance().loadFileIntoImageView(mContext,entity.userlogo,holder.binding?.homeDetailCommentHeaderimage,null)
        }
        holder.binding?.homeDetailCommentUsername?.text = if(entity.nickname.isBlank()) "" else entity.nickname
        holder.binding?.homeDetailCommentContent?.text = entity.content
        holder.binding?.homeDetailCommentAgreeCount?.text = entity.agreenum.toString()

        holder.binding?.homeDetailCommentReply?.let {
            it.tag = entity
            it.setOnClickListener(listener)
        }
    }

    private val listener:View.OnClickListener = object :View.OnClickListener{
        override fun onClick(v: View?) {
            val entity = v?.tag as CommentEntity
            val dialog = ReplyBottomDialog(mContext)
            dialog.show()

            dialog.replyListener = {
                dialog.dismiss()
                Toast.makeText(v.context,it,Toast.LENGTH_SHORT).show()
            }
        }

    }

}
